package com.training1.core.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.training1.core.common.entity.RespJson;
import com.training1.core.common.exception.ExcelException;
import com.training1.core.common.global.signIn.LoginInfo;
import com.training1.core.common.global.signIn.LoginInfoUtil;
import com.training1.core.common.utils.framework.RespJsonFactory;
import com.training1.core.entity.BatchWithDrawalEntity;
import com.training1.core.entity.MemberEntity;
import com.training1.core.entity.User;
import com.training1.core.modules.service.BatchWithDrawalService;
import com.training1.core.modules.service.MemberService;
import com.training1.util.ImportExcel;
import com.training1.util.SequenceNumberUtil;

@Controller
@RequestMapping("batchsetting")
public class BatchWithDrawalController {	
	@Resource
	private BatchWithDrawalService service;
	@Resource
	private MemberService service2;
	
	@RequestMapping(value = { "/", "" })
	public String go() {
		return "yixiang/batchWithDrawal";
	}

	@RequestMapping("xlsx")
	@ResponseBody
	public Map<String,String> upload(MultipartFile file) throws IOException {
		InputStream in = file.getInputStream();
		String originalFilename = file.getOriginalFilename();
		Map<String,String> map = null;
		if (file != null && originalFilename != null && originalFilename.length() > 0) {
			// 存储文件的物理路径
			String file_path = "E:\\upload\\";
			// 文件新名称
			String newfileName = new Date().getTime() + originalFilename.substring(originalFilename.lastIndexOf("."));
			// 创建文件
			File newFile = new File(file_path + newfileName);
			// 判断父路径是否存在
			if (!newFile.getParentFile().exists()) {
				// 创建父路径
				newFile.getParentFile().mkdirs();
			}
			try {
				// 创建文件
				file.transferTo(newFile);
				//验证excel表中数据
				map = service.validate(in,newFile.getAbsolutePath());
				//将文件路径存入map,用于返回给前台，让批量提现获取路径。
				map.put("url", newFile.getAbsolutePath());
			} catch (ExcelException e) {
				e.printStackTrace();
				//存放错误信息
				map = new HashMap<String,String>();
				map.put("result", "err");
				map.put("errMsg", e.getErrMsg().toString().substring(e.getErrMsg().toString().indexOf('[')+1, e.getErrMsg().toString().indexOf(']')));
			} 
		}
		return map;
	}
	
	
	@RequestMapping("withdraw")
	@ResponseBody
	public RespJson withdraw(String path) throws IOException{
		//获取登录用户名
		LoginInfo info = LoginInfoUtil.getLoginInfo();
		String createName = info.getLoginName();		
		Workbook wb = null;
		File file = new File(path);
		//读取文件
		wb = ImportExcel.getwb(file);
		Sheet sheet = wb.getSheetAt(0);
		int lastRowNum = sheet.getLastRowNum();
		//用来存放电话号码，通过电话去查找会员
		List<String> list = new ArrayList<String>();
		//用电话做键BatchWithDrawalEntity对象为值，用于后面再将对象取出设置属性值
		Map<String,BatchWithDrawalEntity> map = new HashMap<String,BatchWithDrawalEntity>();
		//用于判断操作数据库是否成功
		boolean flag = false;
		//度excel
		for(int i=1 ; i <= lastRowNum ; i++){
			//循环读取每行,从第2行开始
			try{
				Row row = sheet.getRow(i);
				if(row == null)continue;
				// 会员手机号
				String cellPhone = ImportExcel.getCellValue(row.getCell(0));
				// 会员姓名
				String memberName = ImportExcel.getCellValue(row.getCell(1));
				// 提现金额
				BigDecimal cash = new BigDecimal(ImportExcel.getCellValue(row.getCell(2)));
				Double money = cash.doubleValue();
				//创建BatchWithDrawalEntity对象，将excel表中每行数据封装到对象中
				BatchWithDrawalEntity bde = new BatchWithDrawalEntity();
				bde.setPhone(cellPhone);
				bde.setName(memberName);
				bde.setMoney(money);
				bde.setCreateBy(createName);
				bde.setUpdateBy(createName);
				//将电话号码和对象作为key,value存到map
				map.put(cellPhone, bde);
				list.add(cellPhone);
			}
			catch(Exception e){
			}
		}
		//通过电话查会员
		List<MemberEntity> memList = service2.findBatch(list);
		//用来存放通过电话查找出的会员对象更新后的对象
		List<MemberEntity> memList1 = new ArrayList<MemberEntity>();
		//用来存放map中BatchWithDrawalEntity对象更新后的对象
		List<BatchWithDrawalEntity> batchList = new ArrayList<BatchWithDrawalEntity>();
		for (MemberEntity memberEntity : memList) {
			//通过电话号码获取对应的对象
			BatchWithDrawalEntity bde1 = map.get(memberEntity.getCellPhone());
			bde1.setOrderNumber(SequenceNumberUtil.generateOrderNumber());
			bde1.setCardNumber(memberEntity.getBankCardId());
			bde1.setBankforCard(memberEntity.getBankName());
			bde1.setStatus(1);
			bde1.setPayStatus(0);
			//用于更新对象信息
			MemberEntity memberEntity1 = memberEntity;
			memberEntity1.setAvaibleCash(new BigDecimal(memberEntity.getAvaibleCash().doubleValue()-bde1.getMoney()));
			memberEntity1.setUpdateBy(createName);
			memList1.add(memberEntity1);
			batchList.add(bde1);
		}
		//插入批量提现的会员和更新对应会员的可提现金额
		flag = service.insertBatch(batchList,memList1)>0;
		if(!flag){
			return RespJsonFactory.buildFailure();
		}
		return RespJsonFactory.buildSuccess();
	}
	
}
